<?php
class Stats extends MY_SecuredController {
	public function __construct() {
		parent::MY_SecuredController();

		$this->requireRole('User');
		$this->load->helper(array('form','url'));

		$this->load->library('converter');

		$this->lang->load('home');
		$this->lang->load('profile');
	}

	public function index($civlid) {
		$this->_preRender($civlid);
			
		$person = PersonModel::getPerson($civlid);
			
		$data['person'] = $person;
		$data['pilot'] = $person->Pilot;

		$uid = $person->Pilot->leonardo_id;
			
		if ($uid) {
			try {
				$data['flights'] = LeonardoFlightModel::getLatestFlightSummaryForUser($uid);
				$data['chartdata'] = LeonardoFlightModel::getShortChartStatsForUser($uid);
				$data['stats'] = LeonardoFlightModel::getStatisticsForUser($uid);
			}
			catch (Exception $e) {
				echo '<pre>'; echo($e); echo "</pre>";
				return;
			}
		}
			
		$this->render('stats/summary', $data);
	}

	public function ajax_stats($civlid, $uid) {
		$this->_preRender($civlid);
		
		$chartData = LeonardoFlightModel::getShortChartStatsForUser($uid);

    // @todo: reduce payload
		/*foreach ($chartData as $d) {
			echo '<pre>'; echo $d['flights_count'].'-'.$d['sum_duration'].'-'.$d['flight_date']; echo "</pre>";
		}*/
		
		echo json_encode($chartData);
	}
	
    public function ajax_yearstats($civlid) {
        $this->_preRender($civlid);
        
        $chartData = LeonardoFlightModel::getYearStatsSummary();

        echo json_encode($chartData);
    }
    
    public function secs2time($secs) {
    	echo sprintf("%d:%02d",$secs/3600,($secs%3600)/60);
    }
}
